/*================================================================
*   Copyright (C) 2020 Sangfor Ltd. All rights reserved.
*   
*   文件名称：test.cpp
*   创 建 者：Ann
*   创建日期：2020年05月15日
*   描    述：
*           1.监控标准输入里面是否有读事件就绪
*
================================================================*/

#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main()
{
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sockfd < 0)
    {
        perror("open");
        return 0;
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(19999);
    addr.sin_addr.s_addr = inet_addr("172.16.99.129");
    bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));

    listen(sockfd, 5);

    //定义
    fd_set readfds;
    FD_ZERO(&readfds);

    //添加, 关心标准输入是否有可读事件产生;
    FD_SET(0, &readfds);
    FD_SET(sockfd, &readfds);

    //监控
    int ret = select(sockfd + 1, &readfds, NULL, NULL, NULL);
    if(ret)
    {
        printf("ret : %d\n", ret);
        //FD_ISSET --> 返回0的时候一定是判断的fd没有在集合当中；
        if(FD_ISSET(0, &readfds) != 0)
        {
            ret = FD_ISSET(sockfd, &readfds);
            printf("FD_ISSET(sockfd, &readfds) --> ret = %d\n", ret);
            char buf[1024] = {0};
            read(0, buf, sizeof(buf) - 1);
            printf("buf:%s\n", buf);
        }
        else if(FD_ISSET(sockfd, &readfds))
        {
            printf("%d\n", sockfd);
            int sockfd1 = accept(sockfd, NULL, NULL);
            printf("sockfd1 : %d\n", sockfd1);
        }
    }

    //去除
    FD_CLR(0, &readfds);
    return 0;
}

